﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Ioc;
using Tisbi.LawFirm.BL;
using Tisbi.LawFirm.BL.Services;
using Tisbi.LawFirm.DAL.Models;
using Tisbi.LawFirm.UI.Views.Controls.Forms;

namespace Tisbi.LawFirm.UI.ViewModel
{
    public class CaseViewModel : BaseViewModel<Cases, ICaseServiceAgent>
    {
        public class MeetingsModel
        {
            public DateTime DateTimeOf { get; set; }
            public Lawsuits Lawsuits { get; set; }
            public Court Court { get; set; }
        }

        public RelayCommand ArchiveCommand { get; private set; }

        // Default ctor
        public CaseViewModel()
        {
            ArchiveCommand = new RelayCommand(ShowArchiveDialog);
            LoadEmployees();
            LoadMeetings();
        }

        protected override void OnSelectedModelItemSelect()
        {
            if (IsInDesignModeStatic)
            {
                return;
            }

            var lawsuitsViewModel = SimpleIoc.Default.GetInstance<LawsuitsViewModel>();
            if (lawsuitsViewModel == null || SelectedModelItem == null)
            {
                return;
            }

            lawsuitsViewModel.ReloadModel(SelectedModelItem.Id);
        }


        public ObservableCollection<MeetingsModel> _meetings;
        public ObservableCollection<MeetingsModel> Meetings
        {
            get
            {
                return _meetings;
            }
            set
            {
                _meetings = value;
                RaisePropertyChanged(() => Meetings);
            }
        }

        public void LoadMeetings()
        {
            var meetings = new List<MeetingsModel>();

            LawsuitsServiceAgent.GetItem((list, exception) =>
            {
                var lawsuitses = list.Where(x => x.HearingDate.HasValue);
                meetings.AddRange(lawsuitses.Select(lawsuitse => new MeetingsModel
                {
                    Lawsuits = lawsuitse,
                    Court = lawsuitse.Court,
                    DateTimeOf = lawsuitse.HearingDate.Value
                }));
            });

            Meetings = new ObservableCollection<MeetingsModel>(meetings);
        }

        private ObservableCollection<Employees> _employeeses;
        public ObservableCollection<Employees> Employeeses
        {
            get { return _employeeses; }
            set
            {
                _employeeses = value;
                RaisePropertyChanged(() => Employeeses);
            }
        }

        private Employees _selectedEmployees;
        public Employees SelectedEmployees
        {
            get { return _selectedEmployees; }
            set
            {
                _selectedEmployees = value;
                LoadModel();
                RaisePropertyChanged(() => SelectedEmployees);
            }
        }

        private bool canArchive;
        public bool CanArchive
        {
            get { return canArchive; }
            set
            {
                canArchive = value;
                RaisePropertyChanged(() => CanArchive);
            }
        }

        private void ShowArchiveDialog()
        {
            throw new NotImplementedException();
        }

        protected override void SetCanProperties()
        {
            base.SetCanProperties();
            CanAdd = !IsBusy && Employeeses != null && Employeeses.Count > 0 && SelectedEmployees != null;
        }

        protected override void ShowEditDialog()
        {
            if (SelectedModelItem == null)
            {
                return;
            }
            LoadEmployees();

            var model = new CasesCRUDViewModel(SelectedModelItem) { Employees = Employeeses };
            ShowEditDialog<CasesCRUDForm>(model, "Карточка изменения дела");
        }

        protected override void ShowCreatedDialog()
        {
            LoadEmployees();

            var newItem = new Cases { Created = DateTime.Now };
            var detailModel = new CasesCRUDViewModel(newItem) { Employees = Employeeses };

            ShowCreatedDialog<CasesCRUDForm>(detailModel, "Карточка создания нового дела");
        }
        
        public void LoadEmployees()
        {
            // Flip busy flag
            IsBusy = true;

            if (!SecurityContextSingleton.GetInstance().IsRootLawyer(false))
            {
                Employees employe = SecurityContextSingleton.GetInstance().CurrentEmploye;

                Employeeses = new ObservableCollection<Employees>(new List<Employees>
                {
                    employe
                });
                
                SelectedEmployees = employe;
                return;
            }

            // Load items
            EmployeeServiceAgent.GetItem
                (
                    EmployeeLoaded
                );
        }

        protected override void LoadModelBySearch()
        {
            IsBusy = true;

            if (SelectedEmployees != null)
            {
                ModelServiceAgent.GetCasesByEmployee
                    (
                        SelectedEmployees.Id,
                        (list, exception) => ModelLoadedByWhere(list, exception, item => item.Title.Contains(SearchCriteria))
                    );
            }
        }

        protected override void LoadModel()
        {
            IsBusy = true;
            
            if (SelectedEmployees != null)
            {
                ModelServiceAgent.GetCasesByEmployee
                    (
                        SelectedEmployees.Id,
                        ModelLoaded
                    );
            }
        }

        private void EmployeeLoaded(List<Employees> entities, Exception error)
        {
            // If no error is returned, set the model to entities
            if (error == null)
            {
                Employeeses = new ObservableCollection<Employees>(entities);
            }
                // Otherwise notify view that there's an error
            else
            {
                Notifyer.NotifyError("Unable to retrieve items", error);
            }

            // Set SelectedItem to the first item
            if (Employeeses != null && Employeeses.Count > 0)
            {
                HasVarnings = false;
                Varnings = string.Empty;

                SelectedEmployees = Employeeses[0];
            }
            else
            {
                HasVarnings = true;

                if (!string.IsNullOrWhiteSpace(Varnings))
                {
                    Varnings += "\n";
                }
                Varnings += "В базе отсудствуют юристы, для продолжения работы добавьте в реестр нового [url=/Views/Pages/Employees.xaml|_top]юриста[/url].";
            }

            // We're done
            IsBusy = false;

            SetCanProperties();
        }
    }
}